﻿using MediatR;
using SqlSugar;
using WarehouseManagement.Application.Command.RequestTransferCommand;
using WarehouseManagement.Infrstructre.Interface;

namespace WarehouseManagement.Application.CommandHandler.RequestTransferCommandHandlers
{
    /// <summary>
    /// 删除调拨申请
    /// </summary>
    public class RequestTransferDelCommandHandler:IRequestHandler<RequestTransferDelCommand,int>
    {
        private readonly ISqlSugarClient db;
        private readonly IRequestTransferRepository _requestTransferRep;
        private readonly IAllocationProductAppRepository _allocationProductAppRep;

        public RequestTransferDelCommandHandler(ISqlSugarClient db, IRequestTransferRepository requestTransferRep, IAllocationProductAppRepository allocationProductAppRep)
        {
            this.db = db;
            this._requestTransferRep = requestTransferRep;
            this._allocationProductAppRep = allocationProductAppRep;
        }

        public async Task<int> Handle(RequestTransferDelCommand request, CancellationToken cancellationToken)
        {
            // 开启事务
            db.Ado.BeginTran();
            try
            {
                var list = (await _requestTransferRep.GetAll()).Where(x => request.RequestTransfersId.Contains(x.RequestTransfersId)).ToList();
                foreach (var material in list)
                {
                    material.IsDel = true;
                    material.DelName = request.DelName;
                    material.DelTime = DateTime.Now;
                    var item = (await _allocationProductAppRep.GetAll()).Where(x => x.RTNumber == material.RTNumber).ToList();
                    foreach (var subpiece in item)
                    {
                        subpiece.IsDel = true;
                        subpiece.DelName = request.DelName;
                        subpiece.DelTime = DateTime.Now;
                        await _allocationProductAppRep.UpdateAsync(subpiece);
                    }
                    await _requestTransferRep.UpdateAsync(material);
                }
                db.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                db.Ado.RollbackTran();
                throw ex;
            }
            finally
            {
                db.Ado.Close();
            }
            return 1;
        }
    }
}
